<template>
  <edit-dialog :centerDialogVisible="visible" tilte="添加成员" @Cancel="handleCancel" @Submit="handleSubmit"
    :width="dialogWidth">
    <template #content>
      <CustomTransfer v-model="selectNodes" :data="data" @change="changeValue" />
    </template>
  </edit-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, defineProps, watch, nextTick, toRaw, computed } from 'vue'
import { useStore } from 'vuex'
import editDialog from '@/components/editDialog/index.vue'
import { ElMessage } from 'element-plus'
import CustomTransfer from './customTransfer.vue'
import { repCompanyShuttle, repCompanyDistribute } from '@/api/rep/company'

interface Option {
  id: number
  key: number
  label: string
  disabled: boolean
}
interface listType {
  id: string,
  label: string,
  isMember?: boolean,
  children?: any[]
}
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  }, selectId: {
    type: String,
    default: '',
  },
  info: {
    type: Object,
    default: () => null,
  },
})

const emit = defineEmits(['cancel', 'ok'])

const store = useStore()
// 弹窗标题
const dialogWidth = ref('610px')
const userInfo = computed(() => store.state.user.userInfo)


const data = ref<Option[]>([])
const selectNodes = ref<listType[]>([])

const changeValue = (value: listType[]) => {
  selectNodes.value = value;
}

const handleSubmit = async () => {
  let array: any[] = [];
  selectNodes.value.forEach(item => {
    array.push({
      memberId: item.id,
      companyId: props.selectId,
      lastMender: {
        id: userInfo.value.userId,
        name: userInfo.value.name,
        userName: userInfo.value.userName,
        organId: userInfo.value.organId || '',
        organName: userInfo.value.organName || ''
      }
    })
  })
  const res = await repCompanyDistribute(array);
  if (res?.code === '1') {
    ElMessage.success('添加人员成功')
    emit('ok')
  } else {
    ElMessage.error(res?.message || '添加人员失败')
  }
}

const handleCancel = () => {
  emit('cancel')
}

const getCompanyShuttle = async () => {
  const res = await repCompanyShuttle({ companyId: props.selectId });
  deepFn(res.data, record => {
    record.id = record.companyId || record.name || record.memberId;
    record.label = record.companyName || record.name || record.memberName;
    if (Array.isArray(record.memberList) && record.memberList.length) {
      record.memberList.forEach(ele => {
        if (!record.children) record.children = [];
        record.children.push({ ...ele, id: ele.memberId, label: ele.memberName, isMember: true });
      })
    }
  }, "children")
  data.value = res.data || [];
}

// const deepFn = (arr = [], fn = (info: any) => { }, key = "children") => {
//   arr.forEach((item: any) => {
//     console.log('item======', item);
//     if (Array.isArray(item[key])) {
//       deepFn(item[key], fn, key)
//     }
//     fn(item);
//   })
// }

const deepFn = (arr = [], fn = (info: any) => { }, key = "children") => {
  arr.forEach((item: any) => {
    if (Array.isArray(item[key])) {
      deepFn(item[key], fn, key)
    }
    fn(item);
  })
}

watch(() => props.visible, (val, oldVal) => {
  if (val) getCompanyShuttle()
  if (val && val !== oldVal) {
    nextTick(() => {
      if (props.info) {
        const info = toRaw(props.info);
      } else {
        // 、、、
      }
    })
  }
})
</script>